import { ElLoading } from "element-plus";
import "element-plus/theme-chalk/src/loading.scss";

import { sleep } from "@/secondary/utils/utils";

interface instanceInterface {
  show?: Function;
  close?: Function;
}

class Loading {
  instance: instanceInterface;
  count: number;

  constructor() {
    this.instance = {};
    this.count = 0; // 全局单例，用count标记单例引用数量
  }

  show(options: object = {}) {
    this.instance = ElLoading.service({
      lock: true,
      text: "加载中",
      background: "rgba(0, 0, 0, 0.7)",
      ...options,
    });
    this.count++;
  }

  async close() {
    await sleep(100); // 防止闪一下的问题出现
    if (this.count > 0) {
      this.count--;
    }
    if (this.count === 0 && this.instance.close) {
      this.instance.close();
    }
  }
}

const $loading = new Loading();

export { $loading };
